import React, { useEffect, useState, useRef } from "react";
import {
  getVideoVoList,
  getVideoCategoryList,
  VideoTilte,
  getCommentVedioList,
  buyVedio,
  addCollectVedio,
  cancelCollectVedio,
} from "../../api/vedio";
import { rmsResult } from "../../api";
import styles from "./video.module.scss";
import { Swiper, Notify } from "react-vant";
import pauseImg from "../../assets/images/video/pause.png";
import commentUrl from "../../assets/images/video/star_down.png";
import payUrl from "../../assets/images/video/toll.png";
import notCollectUrl from "../../assets/images/video/star_down.png";
import writeUrl from "../../assets/images/video/danmu.png";
import collectUrl from "../../assets/images/video/star_light.png";

import { Barra } from "../../components/barrage";
import { VedioInfo } from "../../components/vedioInfo";
export interface VideoList {
  // 摘要
  abstracts: string;
  // 已买数量
  buyNum: number;
  // 健康视频类目id
  categoryId: number;
  // 时长
  duration: number;
  // 健康视频id
  id: number;
  // 原始视频url
  originalUrl: string;
  // 单价
  price: number;
  // 剪切视频url(试看)
  shearUrl: string;
  // 标题
  title: string;
  // 购买
  whetherBuy: number;
  // 收藏  1已经收藏  2没收藏
  whetherCollection: number;
}
export default function Video() {
  // 播放次数
  const [playcount, setPlaycount] = useState(0);
  const videoRealList = [] as HTMLVideoElement[];
  const [videoPlay, setVideoPlay] = useState(false);
  const [videoTopTitles, setVideoTopTitles] = useState<VideoTilte[]>([]);
  const [videoParams, setVideoParams] = useState({
    categoryId: -1,
    count: 100,
    page: 1,
  });
  const [barrageList, setBarrageList] = useState<string[]>([]);
  const [lastPlayIndex, setLastPlayIndex] = useState(0);
  const [videolist, setVideoList] = useState<VideoList[]>([]);
  const [width, setWidth] = useState<string>("0%");
  // 挂载时请求标题
  const getVideoTitle = async () => {
    const resp = (await getVideoCategoryList()) as unknown as rmsResult;
    setVideoTopTitles(resp.result);
    setVideoParams({ ...videoParams, categoryId: resp.result[0].id });
  };

  useEffect(() => {
    getVideoTitle();
  }, []);
  // 获取标题完毕后获取视频列表
  const getVideoList = async () => {
    const resp = (await getVideoVoList(videoParams)) as unknown as rmsResult;

    if (resp.status === "0000") {
      setVideoList(resp.result as unknown as VideoList[]);
      setLastPlayIndex(-1);
      setVideoPlay(false);
    }
  };
  useEffect(() => {
    getVideoList();
  }, [videoParams]);
  // 播放或暂停
  const playOrPause = (num: number) => {
    setVideoPlay(!videoPlay);
    // 播放
    if (!videoPlay) {
      videoRealList[num].play();
      if (playcount == 0) {
        getVedioComment(num);
      }
      setPlaycount(playcount + 1);
    }
    // 暂停
    else {
      videoRealList[num].pause();
    }
  };
  // 划动视频
  const videoChange = (nextIndex: number) => {
    if (videoRealList[lastPlayIndex]) {
      videoRealList[lastPlayIndex].pause();
      videoRealList[nextIndex].play();
      getVedioComment(nextIndex);
      setVideoPlay(true);
    }
    setLastPlayIndex(nextIndex);
  };
  // 切换类型
  const nextType = (id: number) => {
    console.log(lastPlayIndex);
    setVideoParams({
      ...videoParams,
      categoryId: videoTopTitles[id - 1].id + 1,
    });
  };
  // 获取弹幕
  const getVedioComment = async (index: number) => {
    const videoId = videolist[index].id;
    const resp = (await getCommentVedioList(videoId)) as any;
    const result = resp.result.map((v: any) => v.content).slice(0, 100);
    console.log(result);

    setBarrageList(result);
  };
  // 收藏
  const oprationCollect = async (v: VideoList) => {
    if (v.whetherCollection === 2) {
      const { status, message } = (await addCollectVedio(v.id)) as any;
      if (status === "0000") {
        Notify.show({ type: "success", message });
        getVideoList();
      } else if (status === "9999") {
        Notify.show({ type: "danger", message });
      }
    } else {
      const { status, message } = (await cancelCollectVedio(v.id)) as any;
      if (status === "0000") {
        Notify.show({ type: "success", message });
        getVideoList();
      } else if (status === "9999") {
        Notify.show({ type: "danger", message });
      }
    }
  };
  // 购买视频
  const buy = async (v: VideoList) => {
    const { status, message } = (await buyVedio(v.id, v.price)) as any;
    if (status === "0000") {
      Notify.show({ type: "success", message });
    } else if (status === "9999") {
      Notify.show({ type: "danger", message });
    }
  };
  return videolist.length > 0 ? (
    <div className={styles.video}>
      <Swiper
        className={styles.swiper}
        vertical
        indicator={false}
        loop={false}
        stuckAtBoundary
        rubberband={false}
        onChange={(index) => videoChange(index)}
      >
        {videolist.map((v, i) => {
          return (
            <Swiper.Item key={v.id}>
              <video
                ref={(ref) => {
                  videoRealList[i] = ref as HTMLVideoElement;
                }}
                onClick={() => playOrPause(i)}
                onTimeUpdate={(e) => {
                  const tar = e.target as HTMLVideoElement;
                  setWidth((tar.currentTime / tar.duration) * 100 + "%");
                }}
                controls={false}
                preload="auto"
              >
                <source src={v.whetherBuy === 1 ? v.originalUrl : v.shearUrl} />
              </video>
              {/* 暂停 */}
              <div className={styles.pause}>
                <img
                  src={pauseImg}
                  alt=""
                  style={{ display: videoPlay ? "none" : "block" }}
                  onClick={() => playOrPause(i)}
                />
              </div>
              {/* 弹幕 */}
              {barrageList.length > 0 && i === lastPlayIndex && (
                <div className={styles["barra"]}>
                  <Barra barrageList={barrageList} autoPlay={videoPlay}></Barra>
                </div>
              )}
              {/* 右侧icon */}
              <div className={styles["right"]}>
                {v.whetherBuy === 1 ? (
                  <img src={commentUrl} alt="" />
                ) : (
                  <img src={payUrl} alt="" onClick={() => buy(v)} />
                )}
                <img
                  src={v.whetherCollection === 2 ? notCollectUrl : collectUrl}
                  alt=""
                  onClick={() => oprationCollect(v)}
                />
                <img src={writeUrl} alt="" />
              </div>
              {/* 上箭头 */}
              <VedioInfo
                v={v}
                width={i === lastPlayIndex ? width : "0%"}
                touchMove={(progerss) => {
                  const el = videoRealList[lastPlayIndex];
                  el.currentTime = progerss * el.duration;
                }}
              ></VedioInfo>
            </Swiper.Item>
          );
        })}
      </Swiper>
      {/* 头部切换视频类型 */}
      <div className={styles.header}>
        {/* 上一类型 */}
        {videoTopTitles[videoParams.categoryId - 2] ? (
          <div
            className={styles.lastVideoType}
            onClick={() => nextType(videoParams.categoryId - 2)}
          >
            {videoTopTitles[videoParams.categoryId - 2].name}
          </div>
        ) : (
          <div className={styles.lastVideoType}></div>
        )}
        {/* 当前类型 */}
        <div className={styles.VideoType}>
          {videoTopTitles[videoParams.categoryId - 1].name}
        </div>
        {/* 下一类型 */}
        {videoTopTitles[videoParams.categoryId] ? (
          <div
            className={styles.nextVideoType}
            onClick={() => nextType(videoParams.categoryId)}
          >
            {videoTopTitles[videoParams.categoryId].name}
          </div>
        ) : (
          <div className={styles.nextVideoType}></div>
        )}
      </div>
    </div>
  ) : (
    <div>加载中</div>
  );
}
